package com.tf8.treasure.service.impl;

import com.tf8.treasure.entity.SmsLog;
import com.tf8.treasure.entity.SmsLogExample;
import com.tf8.treasure.mapper.SmsLogMapper;
import com.tf8.treasure.service.SmsLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class SmsLogServiceImpl implements SmsLogService {

    @Autowired
    private SmsLogMapper smsLogMapper;


    @Override
    public String verify(String mobile, String code) {
        SmsLogExample example = new SmsLogExample();
        example.createCriteria().andCodeEqualTo(code).andMobileEqualTo(mobile)
                .andExpTimeGreaterThanOrEqualTo(new Date());
        List<SmsLog> smsLogs = smsLogMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(smsLogs)) {
            return "验证码无效";
        }
        return null;
    }

    @Override
    public String obtainCode(String mobile) {
        SmsLogExample example = new SmsLogExample();
        example.createCriteria().andMobileEqualTo(mobile)
                .andExpTimeGreaterThanOrEqualTo(new Date());
        List<SmsLog> smsLogs = smsLogMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(smsLogs)) {
            String code="123456";
            SmsLog smsLog=new SmsLog();
            smsLog.setCode(code);
            smsLog.setMobile(mobile);
            smsLog.setContent("恋爱宝典 验证码"+code+"五分钟过期");
            smsLog.setExpTime(new Date(System.currentTimeMillis()+(5*60*1000)));
            smsLog.setSmsType("1");
            smsLog.setPlatform("test");
            smsLog.setCreateTime(new Date());
            smsLog.setUpdateTime(new Date());
            smsLogMapper.insertSelective(smsLog);
            return code;
        }
        return smsLogs.get(0).getCode();
    }
}
